package com.matt.controller;

import com.dotflat.util.excelUtil.StringUtils;
import com.google.common.base.Splitter;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.commons.exception.BusinessException;
import com.matt.commons.model.StatusResponse;
import com.matt.domain.Children;
import com.matt.domain.ChildrenExtendInfo;
import com.matt.domain.photoalbum.PhotoAlbumStatic;
import com.matt.foundation.constant.ChildrenConstant;
import com.matt.foundation.model.ErrorCode;
import com.matt.foundation.utils.DateUtil;
import com.matt.repository.ChildrenExtendInfoRepository;
import com.matt.repository.ChildrenRepository;
import com.matt.repository.base.ChildChildrenExtendRepository;
import com.matt.repository.base.ChildrenCheckRecordRepository;
import com.matt.repository.photoAlbum.PhotoAlbumStaticRepository;
import com.matt.repository.rel.RelClassesChildrenRepository;
import com.matt.service.ChildrenService;
import com.matt.service.ClassesService;
import com.matt.service.WeekPaperService;
import com.matt.service.WxPushService;
import com.matt.service.remoteCall.SsoCallService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * *******************************
 * Created by Ron.
 * form com.matt
 * on 2018/7/26
 * *******************************
 */
@RestController
@RequestMapping(value = "/other_system")
public class OtherSystemController {

    @Autowired
    private ChildrenService childrenService;

    @Autowired
    private ChildrenRepository childrenRepository;

    @Autowired
    private ChildrenCheckRecordRepository childrenCheckRecordRepository;

    @Autowired
    private ClassesService classesService;

    @Autowired
    private WeekPaperService weekPaperService;

    @Autowired
    private RelClassesChildrenRepository relClassesChildrenRepository;

    @Autowired
    private SsoCallService ssoCallService;

    @Autowired
    private WxPushService wxPushService;

    @Autowired
    private ChildChildrenExtendRepository childChildrenExtendRepository;

    @Autowired
    private ChildrenExtendInfoRepository childrenExtendInfoRepository;

    @Autowired
    private PhotoAlbumStaticRepository albumStaticRepository;

    /**
     * 新增未激活宝宝
     *
     * @return
     */
    @RequestMapping(value = "/create_child")
    public StatusResponse createChild(String childrenName, String nickName, Integer gender, String birthday, String areaId, String address, String crmClienteleId, String name, String phone, String company, String relation, String staffId,String province,String city,String district,String detailedAddress,String education,String position,String email) {
        Children c = childrenService.getByCrmClienteleId(crmClienteleId);

        if (c == null) {
            Children children = Children.of(childrenName, Objects.isNull(nickName) ? "" : nickName, gender, DateUtil.parseToDate(birthday), areaId, Objects.isNull(address) ? "" : address, crmClienteleId, staffId);
            childrenService.add(children, phone, name, company, relation, province, city, district, detailedAddress, education, position,email);
        }

        return StatusResponse.success();
    }

    /**
     * 新增未激活宝宝
     */
    @RequestMapping(value = "/active_child")
    public StatusResponse activeChild(String clienteleId, String contractBeginDate, String contractEndDate, String productJson) {
        childrenService.active(clienteleId, contractBeginDate, contractEndDate, productJson);
        return StatusResponse.success();
    }

    @RequestMapping(value = "/notify_pay_order")
    public StatusResponse notifyPayOrder(String areaId, String childrenId, String childrenName, String teacherName,
                                         String orderTitle, String amount, String payType,
                                         Integer resourceType, String resourceId) {
//        DEPOSIT(0, "充值", 0),
//                PRODUCT(1, "收费项目", 0),
//                PHOTOPRINT(2, "相册打印", 0);
        if (resourceType != null && resourceType == 2){
            if (StringUtils.isNotEmpty(resourceId)){
                Optional<PhotoAlbumStatic> op = albumStaticRepository.findById(resourceId);
                if (op.isPresent()){
                    PhotoAlbumStatic albumStatic = op.get();
                    albumStatic.setPaied(true);
                    albumStaticRepository.save(albumStatic);
                }
            }


            return StatusResponse.success();
        }

        wxPushService.pushPayNotify(areaId, childrenId, childrenName, teacherName, orderTitle, amount, payType);
        return StatusResponse.success();
    }

    /**
     * 结束所有托班课程
     */
    @RequestMapping(value = "/over_all_nursery_contract")
    public StatusResponse overAllNurseryContract(String clienteleId, String remark, String staffId) {
        StaffDTO staff = ssoCallService.getStaffDTO(staffId);

        Children children = childrenRepository.findByCrmClienteleId(clienteleId);

        childrenService.overNursery(staff, children.getId(), remark);

        return StatusResponse.success();
    }

    /**
     * 结束所有早教课程
     */
    @RequestMapping(value = "/over_all_early_contract")
    public StatusResponse overAllEarlyContract(String clienteleId, String remark, String staffId) {

        StaffDTO staff = ssoCallService.getStaffDTO(staffId);

        Children children = childrenRepository.findByCrmClienteleId(clienteleId);

        childrenService.overEarly(staff, children.getId(), remark);
        return StatusResponse.success();
    }

    /**
     * 减去早教课程
     */
    @RequestMapping(value = "/over_early_contract")
    public StatusResponse subtractEarlyCourse(String clienteleId, Integer count, String remark, String staffId) {
        Children children = childrenRepository.findByCrmClienteleId(clienteleId);
        if (count <= 0) {
            throw new BusinessException(ErrorCode.PARAM_CAN_NOT_BLANK, "参数错误");
        }

        StaffDTO staff = ssoCallService.getStaffDTO(staffId);

        childrenService.changeEarlyCourseCount(staff, children.getId(), -count, remark);
        return StatusResponse.success();
    }

    /**
     * 获取宝宝签到数量
     *
     * @param date
     * @param areaId
     * @return
     */
    @RequestMapping(value = "/check_in_count")
    public StatusResponse getChildCheckInNum(String date, String areaId) {
        Integer checkInCount = childrenCheckRecordRepository.findCheckInCountByDateAndAreaId(date, areaId);
        return StatusResponse.success(checkInCount);
    }

    /**
     * 获取宝宝签退数量
     *
     * @param date
     * @param areaId
     * @return
     */
    @RequestMapping(value = "/check_out_count")
    public StatusResponse getChildCheckOutNum(String date, String areaId) {
        Integer checkOutCount = childrenCheckRecordRepository.findCheckOutCountByDateAndAreaId(date, areaId);
        return StatusResponse.success(checkOutCount);
    }

    /**
     * 获取班级数量
     *
     * @param areaId
     * @return
     */
    @RequestMapping(value = "classes_count")
    public StatusResponse getClassesNum(String areaId) {
        Integer count = classesService.getActiveClassesByArea(areaId).size();
        return StatusResponse.success(count);
    }

    /**
     * 获取园区的周报信息
     *
     * @param areaId
     * @return
     */
    @RequestMapping(value = "/get_area_week_data")
    public StatusResponse getAreaWeekData(String areaId, String date) {
        return StatusResponse.success(weekPaperService.getAreaWeekData(areaId, date));
    }

    /**
     * 获取这周进园的宝宝数
     *
     * @param areaId
     * @return
     */
    @RequestMapping(value = "/get_teacher_week_data")
    public StatusResponse getTeacherWeekData(String areaId, String staffId, String date) {
        return StatusResponse.success(weekPaperService.getTeacherWeekData(areaId, staffId, date));
    }

    /**
     * 获取老师这周 （评测孩子数）
     *
     * @param staffId
     * @return
     */
    @RequestMapping(value = "/get_num_by_staffId")
    public StatusResponse getExamineNum(String staffId, String date) {
        return StatusResponse.success(weekPaperService.getExamineNum(staffId, date));
    }

    /**
     * 查询当天客户对应孩子的入园数
     *
     * @return
     */
    @RequestMapping(value = "get_clientele_check_in_count")
    public StatusResponse getClienteleCheckInCount(String clienteleIds, String date) {
        Integer checkInCount = childrenCheckRecordRepository.findCheckInCountByDateAndClienteleIds(date, Splitter.on(",").trimResults().splitToList(clienteleIds));
        return StatusResponse.success(checkInCount);
    }


    /**
     * 查询客户对应孩子的指定时间入园数
     *
     * @return
     */
    @RequestMapping(value = "get_clienteleId_check_in_count")
    public StatusResponse getClienteleIdCheckInCount(String clienteleId, String beginDate, String endDate) {
        Integer checkInCount = childrenCheckRecordRepository.findCheckInCountByDateAndClienteleId(clienteleId, beginDate, endDate);
        return StatusResponse.success(checkInCount);
    }


    /**
     * 查询客户对应孩子的指定时间请假总数
     *
     * @return
     */
    @RequestMapping(value = "get_clienteleId_leave_count")
    public StatusResponse getClienteleIdLeaveCount(String clienteleId, String beginDate, String endDate) {
        Integer checkInCount = childrenCheckRecordRepository.findLeaveCountByDateAndClienteleId(clienteleId, beginDate, endDate);
        return StatusResponse.success(checkInCount);
    }


    /**
     * 查询每天老师宝宝的入园数
     *
     * @return
     */
    @RequestMapping(value = "get_teacher_check_in_count")
    public StatusResponse getTeacherCheckInCount(String staffId, String date) {
        Integer checkInCount = childrenCheckRecordRepository.getTeacherCheckInCount(staffId, date);
        return StatusResponse.success(checkInCount);
    }


    /**
     * 查询每天老师宝宝的离园数
     *
     * @return
     */
    @RequestMapping(value = "get_teacher_check_out_count")
    public StatusResponse getTeacherCheckOutCount(String staffId, String date) {
        Integer checkInCount = childrenCheckRecordRepository.getTeacherCheckOutCount(staffId, date);
        return StatusResponse.success(checkInCount);
    }

    /**
     * 查询每天保育员的入园数
     *
     * @param staffId
     * @param date
     * @return
     */
    @RequestMapping(value = "get_nursery_check_in_count")
    public StatusResponse getNurseryCheckInCount(String staffId, String date) {
        Integer checkInCount = childrenCheckRecordRepository.getNurseryCheckInCount(staffId, date);
        return StatusResponse.success(checkInCount);
    }

    /**
     * 查询每天保育员的离园数
     *
     * @param staffId
     * @param date
     * @return
     */
    @RequestMapping(value = "get_nursery_check_out_count")
    public StatusResponse getNurseryCheckOutCount(String staffId, String date) {
        Integer checkInCount = childrenCheckRecordRepository.getNurseryCheckOutCount(staffId, date);
        return StatusResponse.success(checkInCount);
    }

    /**
     * 查询园区托班数
     *
     * @param areaId 园区id
     * @param date   日期
     * @return
     */
    @RequestMapping(value = "/get_area_nursery_classes_count")
    public StatusResponse getAreaNurseryClassesCount(String areaId, String date) {
        Integer count = classesService.getAreaNurseryClassesCount(areaId, date, false);
        return StatusResponse.success(count);
    }

    /**
     * 本班每月出勤孩子总数（教师）[数据按照每天存储]
     *
     * @param staffId
     * @param date
     * @return
     */
    @RequestMapping(value = "/get_teacher_child_check_in_count")
    public StatusResponse getTeacherChildCheckInCount(String staffId, String date) {
        Integer count = classesService.getTeacherChildCheckInCount(staffId, date);
        return StatusResponse.success(count);
    }

    /**
     * 园区每月出勤孩子总数
     *
     * @param areaId
     * @param date
     * @return
     */
    @RequestMapping(value = "/get_area_child_check_in_count")
    public StatusResponse getAreaChildCheckInCount(String areaId, String date) {
        Integer count = childrenCheckRecordRepository.getAreaChildCheckInCount(areaId, date);
        return StatusResponse.success(count);
    }

    /**
     * 冻结/解冻宝宝删除宝宝班级关系
     *
     * @param areaId
     * @return
     */
    @RequestMapping(value = "/update_child_info")
    public StatusResponse updateChildInfo(String areaId, String clienteleId, String childName, boolean freeze) {

        Children children = childrenRepository.findByCrmClienteleIdAndNameAndAreaId(clienteleId, childName, areaId);
        if (freeze) {
            children.setStatus(ChildrenConstant.ChildrenStatus.FREEZE.codeOf());
            childrenRepository.save(children);
            relClassesChildrenRepository.deleteByChildrenId(children.getId());
        } else {
            children.setStatus(ChildrenConstant.ChildrenStatus.ACTIVE.codeOf());
            childrenRepository.save(children);
        }

        return StatusResponse.success();
    }

    @RequestMapping(value = "/get_children_course")
    public StatusResponse updateChildInfo(String mobile) {
        //TODO:
        return StatusResponse.success();
    }

    @ApiOperation(value = "客户 - 指定时间段出勤数统计")
    @PostMapping("/clientele_attendance_count")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "clienteleId", value = "客户id", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "areaId", value = "园区ID", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "startTime", value = "开始时间yyyy-MM-dd", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "endTime", value = "结束时间yyyy-MM-dd", required = true, dataType = "string"),
    })
    public StatusResponse areaTypeNameCount(String areaId, String clienteleId, String startTime, String endTime) {
        Integer count = childrenService.clienteleAttendanceCount(areaId, clienteleId, startTime, endTime);
        return StatusResponse.success(count);
    }

    @ApiOperation(value = "客户 - 课程时间总数统计")
    @PostMapping("/clientele_course_time_count")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "clienteleId", value = "客户id", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "areaId", value = "园区ID", required = true, dataType = "string"),
    })
    public StatusResponse areaTypeNameCount(String areaId, String clienteleId) {
        Map map = childrenService.clienteleCourseTimeCount(areaId, clienteleId);
        return StatusResponse.success(map);
    }

    @ApiOperation(value = "添加宝宝摄像头时间")
    @PostMapping("/add_camera_time")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "crmClienteleId", value = "客户id", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "month", value = "月", required = true, dataType = "int"),
    })
    public StatusResponse add_camera_time(String crmClienteleId, Integer month) {
        ChildrenExtendInfo childrenExtendInfo = childChildrenExtendRepository.findCameraTime(crmClienteleId);
        if (Objects.isNull(childrenExtendInfo)) {
            throw new BusinessException(ErrorCode.STAFF_NOT_EXIST, "家长不存在");
        }
        Date date = new Date();
        if (childrenExtendInfo.getCameraValidTo().getTime() > new Date().getTime()) {
            date = childrenExtendInfo.getCameraValidTo();
        }
        date.setTime(date.getTime() + (month * 2592000000L));
        childrenExtendInfo.setCameraValidTo(date);
        childrenExtendInfoRepository.save(childrenExtendInfo);
        return StatusResponse.success();
    }


    @ApiOperation(value = "查询学生信息")
    @PostMapping("/childrenId_by_children")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "childrenId", value = "学生id", required = true, dataType = "string"),
    })
    public StatusResponse childrenIdGetChildren(String childrenId) {
        Children children = childrenService.getById(childrenId);
        return StatusResponse.success(children);
    }



}